<?php


namespace App\Http\Controllers\Admin;
use App\Exports\UserExport;
use App\Models\User;
use Dingo\Api\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class UserController extends BaseController
{
    public function index(Request $request) {
        $shop_name = $request->input('shop_name');
        $is_export = $request->input('is_export', false);

        if ($is_export) {
            $limit = 50000;
        } else {
            $limit = $request->get('per_page',20);
        }


        $users = User::join('merchants', function ($join) use($shop_name) {
            $join->on('merchants.id', 'users.merchant_id');
            if ($shop_name)
                $join->where('shop_name', 'like', '%' . $shop_name . "%");
            return $join;
        })->orderBy('users.id', 'desc')->select('users.*', 'merchants.shop_name')->orderBy("users.id", "desc")->paginate($limit);

        foreach ($users as &$user) {
            $user->rec_toal = $user->rec_total;
            $user->rec_phone = $user->rec_phone;
        }

        if ($is_export) {
            $res = $users->toArray();
            return Excel::download(new UserExport($res['data']),  date('Y-m-d') . "会员记录.xlsx");
        }

        return $this->paginate($users);
    }

    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:users'
        ]);
        $id = \request("id");
        $user = User::find($id);
        $user->rec_phone = $user->rec_phone;
        $user->age = $user->age;
        $user->merchant;
        return $this->success($user);
    }



}

